package com.ithinks.flow.common.utils.protocol.netty.serializable.msgpack;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.LineBasedFrameDecoder;

import java.net.InetSocketAddress;

/**
 * @Description
 * @ClassName ClientMsgPackEcho
 * @Author MR.LI
 * @date 2020.12.09 18:46
 */
public class ClientMsgPackEcho {

    private final String host;

    public ClientMsgPackEcho(String host){ this.host = host;}

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            final Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,9999))
                    .handler(new ChannelInitializerImp());
            ChannelFuture f= b.connect().sync();
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    private static class ChannelInitializerImp extends ChannelInitializer<Channel>{

        @Override
        protected void initChannel(Channel channel) throws Exception {
            //这里设置报文的包头长度来避免粘包
            channel.pipeline().addLast("frameEncoder",new LengthFieldPrepender(2));
            //对发送的数据进行序列化
            channel.pipeline().addLast(new MsgPackEncoder());
            //处理服务器的应答
            channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
            channel.pipeline().addLast(new MsgPackClientHandler(5));
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ClientMsgPackEcho("127.0.0.1").start();
    }

}
